package com.jorado.httpclient;

import com.jorado.core.utility.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;

public class HttpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    public HttpUtils() {
    }

    public static String get(String url) {
        return get(url, 2000);
    }

    public static String get(String url, int timeout) {
        return get(url, timeout, input -> input);
    }

    public static <T> T get(String url, Function<String, T> serializeFunction) {
        return get(url, 5000, serializeFunction);
    }

    public static <T> T get(String url, int timeout, Function<String, T> serializeFunction) {
        return get(url, 2000, timeout, serializeFunction);
    }

    public static <T> T get(String url, int connectTimeout, int readTimeout, Function<String, T> serializeFunction) {
        InputStreamReader isr = null;

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

            conn.setRequestMethod("GET");

            if (connectTimeout < 0) {
                connectTimeout = 2000;
            }

            if (readTimeout < 0) {
                readTimeout = 5000;
            }

            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);

            conn.connect();

            isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
            String response = IOUtils.toString(isr);
            return serializeFunction.apply(response);
        } catch (Throwable ex) {
            LOGGER.error("http get url error,url=" + url, ex);
            return null;
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    }
}